package cn.bonoon.services.plugins;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.TypedQuery;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.bonoon.core.IMessageEditor;
import cn.bonoon.core.plugins.MessageService;
import cn.bonoon.entities.plugins.MessageAcceptEntity;
import cn.bonoon.entities.plugins.MessageEntity;
import cn.bonoon.kernel.events.OperateEvent;
import cn.bonoon.kernel.support.services.AbstractService;

@Service
@Transactional(readOnly = true)
public class MessageServiceImpl extends AbstractService<MessageEntity> implements MessageService {

	@Override
	@Transactional
	public void save(Long senderId, String senderName, String title, String content, Long... accepterIds) {
		MessageEntity message = new MessageEntity();
		message.setCreateAt(new Date());
		message.setTitle(title);
		message.setContent(content);
		message.setStatus(MessageService.PEOPLE_MESS);
		message.setSenderId(senderId);
		message.setSenderName(senderName);
		message.setTotal(accepterIds.length);
		List<MessageAcceptEntity> accepts = new ArrayList<MessageAcceptEntity>();
		MessageAcceptEntity messageAccept;
		for (Long accepterId : accepterIds) {
			messageAccept = new MessageAcceptEntity();
			messageAccept.setAccepterId(accepterId);
			messageAccept.setHasRead(false);
			messageAccept.setMessage(message);
			entityManager.persist(messageAccept);
			accepts.add(messageAccept);
		}
		message.setAccepts(accepts);
		entityManager.persist(message);
	}

	@Override
	public List<MessageEntity> getSendMessage(Long senderId, Long page) {
		String ql = "from MessageEntity m where m.status=1 and m.senderId=:senderId order by m.createAt desc";
		TypedQuery<MessageEntity> tqSelect = __query(MessageEntity.class, ql);
		tqSelect.setParameter("senderId", senderId);
		tqSelect.setFirstResult((int) ((page - 1) * 10));
		tqSelect.setMaxResults(10);
		return tqSelect.getResultList();
	}

	@Override
	protected MessageEntity __save(OperateEvent event, MessageEntity entity) {
		IMessageEditor mEditor = (IMessageEditor) event.getSource();
		Long[] acceptsid = mEditor.getAcceptsid();
		if (null != acceptsid && acceptsid.length > 0) {
			entity.setStatus(MessageService.PEOPLE_MESS);
			entity.setSenderId(event.getId());
			entity.setSenderName(event.getUsername());
			entity.setTotal(acceptsid.length);
			List<MessageAcceptEntity> accepts = new ArrayList<MessageAcceptEntity>();
			MessageAcceptEntity messageAccept;
			for (Long acceptid : acceptsid) {
				messageAccept = new MessageAcceptEntity();
				messageAccept.setAccepterId(acceptid);
				messageAccept.setHasRead(false);
				messageAccept.setMessage(entity);
				entityManager.persist(messageAccept);
				accepts.add(messageAccept);
			}
			entity.setAccepts(accepts);
		}
		return super.__save(event, entity);
	}

}
